package com.activity.service.impl;

import com.activity.common.util.NewType;
import com.activity.common.util.RequestUtils;
import com.activity.entity.News;
import com.activity.entity.NewsSearchCondition;
import com.activity.mapper.NewsMapper;
import com.activity.service.NewsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class NewsServiceImpl implements NewsService {
    @Resource
    private NewsMapper newsMapper;

    //添加一个活动信息
    @Override
    public boolean insert(News news) {
        news.setTime(new Date());
        int insert = newsMapper.insert(news);
        return insert != 0;
    }

    //删除活动信息
    @Override
    public boolean delete(Integer ID) {
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", ID);
        int delete = newsMapper.delete(queryWrapper);
        return delete != 0;
    }

    //查询所有活动信息
    @Override
    public List<News> selectAll() {
        List<News> news = newsMapper.selectList(null);
        return news;
    }
    public List<News> selectByAuthor(String Author) {
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        //根据活动的标题做个查询
        queryWrapper.eq("Author", Author);
        List<News> news = newsMapper.selectList(queryWrapper);
        return news;
    }
    //只返回已启用的活动
    public List<News> selectByEnableNews() {
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        //根据活动的标题做个查询
        queryWrapper.eq("State", NewType.OK);
        List<News> news = newsMapper.selectList(queryWrapper);
        return news;
    }
    public List<News> selectByDeptAndNotExamine(Integer deptid) {
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        //根据活动的标题做个查询
        queryWrapper.eq("Departmentid", deptid);



        queryWrapper.ne("State",NewType.OK);

        List<News> news = newsMapper.selectList(queryWrapper);
        return news;
    }

    //更改活动信息
    @Override
    public boolean update(News news) {
        QueryWrapper<News> wrapper = new QueryWrapper<>();
        wrapper.eq("id", news.getId());
        int update = newsMapper.update(news, wrapper);
        return update != 0;
    }

    @Override
    public List<News> searchByName(String title) {
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        //根据活动的标题做个查询
        queryWrapper.like("Title", title);
        List<News> newsList = newsMapper.selectList(queryWrapper);
        return newsList;
    }


    @Override
    public boolean save(News news) {
        if (news.getId() == null){
            news.setAuthor(RequestUtils.getCurrentUsername());
            return insert(news);
        }
        news.setState(com.activity.common.constact.NewType.NO);
        return newsMapper.updateById(news) != 0;
    }

    public boolean examine(Integer id) {
        boolean examine = newsMapper.examine(id);
        return examine;
    }

    /**
     * 根据日期查询
     *
     * @param targetDate
     * @return
     */
    @Override
    public List<News> selectByDate(Date targetDate) {
        return newsMapper.selectByDate(targetDate);
    }

    /**
     * 查询一个月的
     */
    @Override
    public Map<String, List<News>> selectByMonthDate(String date) {

        String strDateFormat = "yyyy-MM-dd";

        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);

        Date parse = null;
        Map<String, List<News>> resultMap = new HashMap<>();
        try {
            parse = sdf.parse(date);
            Calendar calendar = Calendar.getInstance();

            calendar.setTime(parse);

//            calendar.add(Calendar.DAY_OF_MONTH, -1);22
            calendar.set(Calendar.DATE, 1);

            Integer targetMonth = calendar.get(Calendar.MONTH);

//            System.out.println(targetMonth);
            while (calendar.get(Calendar.MONTH) == targetMonth) {
                String key = String.format("%d-%02d-%02d"
                        , calendar.get(Calendar.YEAR)
                        , calendar.get(Calendar.MONTH) + 1
                        , calendar.get(Calendar.DATE)
                );

                int week = calendar.get(Calendar.DAY_OF_WEEK);
                resultMap.put(key, selectByDate(calendar.getTime())
                        .stream()
                        .filter(f ->
                                f.getWeekCondition().contains(week))
                        .collect(Collectors.toList()));
                calendar.add(Calendar.DATE, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }


        return resultMap;
    }


    public Map<String, List<News>> selectByMonthDate(Integer departmentId, String date) {

        Map<String, List<News>> sourceMap = selectByMonthDate(date);
        Map<String, List<News>> resultMap = new HashMap<>();
        sourceMap.keySet().forEach(item -> {

            List<News> result = sourceMap.get(item).stream()
                    .filter(f -> departmentId.equals(f.getDepartmentid()))
                    .collect(Collectors.toList());
            resultMap.put(item, result);

        });

        return resultMap;


    }

    /**
     * 根据多个条件进行搜索
     *
     * @param condition
     * @see NewsSearchCondition
     */
    public Map<String, List<News>> searchByCondition(NewsSearchCondition condition) {
        Map<String, List<News>> resultMap = new HashMap<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(condition.getStartDate());

        while (!calendar.getTime().after(condition.getEndDate())) {
            List<News> currentDayNews = new ArrayList<>();
            List<News> searchResult = selectByDate(calendar.getTime());
            searchResult.forEach(news -> {
                Integer currentDayWeek = calendar.get(Calendar.DAY_OF_WEEK);
//                System.out.println("活动具体时间: " + news.getWeekCondition()
//                        + " 当前星期: " + currentDayWeek);
                // 如果具体时间匹配
                boolean isLike = true;
                boolean newsWeekLike = false;
                if(condition.getWeeks().size() > 0){
                    for (Integer newWeek : news.getWeekCondition()) {
                        if(condition.getWeeks().contains(newWeek)){
                            newsWeekLike = true;
                        }
                    }
                    if(!newsWeekLike){
                        isLike = false;
                    }
                }

                if (!news.getWeekCondition().contains(currentDayWeek)) {
                    isLike = false;
                }
                if(condition.getDeptId() != null && !news.getDepartmentid().equals(condition.getDeptId())){
                    isLike = false;
                }
                if(StringUtils.isNotBlank(condition.getNewsTitle())){
                    if (!news.getTitle().contains(condition.getNewsTitle())){
                        isLike = false;
                    }
                }
                if (StringUtils.isNotBlank(condition.getNewsContent())) {
                    if (!news.getContent().contains(condition.getNewsContent())) {
                        isLike = false;
                    }
                }
                if (StringUtils.isNotBlank(condition.getAuthor())) {
                    if (!news.getAuthor().contains(condition.getAuthor())) {
                        isLike = false;
                    }
                }
                if (StringUtils.isNotBlank(condition.getPartner())) {
                    if (!news.getPartner().contains(condition.getPartner())) {
                        isLike = false;
                    }
                }
                if (StringUtils.isNotBlank(condition.getKeyword())) {
                    if (!news.getKeyword().contains(condition.getKeyword())) {
                        isLike = false;
                    }
                }
                if (condition.getCategoryId() != null) {
                    if (!news.getCategoryid().equals(condition.getCategoryId())) {
                        isLike = false;
                    }
                }
                if(isLike){
                    currentDayNews.add(news);
                }


            });
            String key = String.format("%d-%02d-%02d"
                    , calendar.get(Calendar.YEAR)
                    , calendar.get(Calendar.MONTH) + 1
                    , calendar.get(Calendar.DATE)
            );
            if (currentDayNews.size() > 0){
                resultMap.put(key, currentDayNews);
            }

            calendar.add(Calendar.DATE, 1);
        }

        return resultMap;

    }





}



